package cn.czh.org.service.impl;

import cn.czh.basic.service.impl.BaseServiceImpl;

import cn.czh.basic.util.Md5Utils;
import cn.czh.basic.util.StrUtils;
import cn.czh.org.domain.Employee;

import cn.czh.org.mapper.EmployeeMapper;
import cn.czh.org.service.IEmployeeService;

import cn.czh.user.domain.Logininfo;
import cn.czh.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void add(Employee employee) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        //2.保存logininfo信息
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        //3.保存员工信息
        employee.setLogininfo_id(logininfo.getId());
        super.add(employee);

        if (employee.getRole_id()!=null){
            //添加中间表数据
            employeeMapper.addEmployeeRole(employee);
        }
    }

    public Logininfo employee2Logininfo(Employee employee){
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则进行拷贝
        BeanUtils.copyProperties(employee,logininfo);
        //当前对象是店铺管理员
        logininfo.setType(0);
        return logininfo;
    }



    @Override
    public void del(Long id) {
        Employee employee = employeeMapper.loadById(id);

        //删除登录信息表数据
        logininfoMapper.remove(employee.getLogininfo_id());

        //删除中间表数据
        employeeMapper.delEmployeeRoleByEmpId(id);

        //删除employee表数据
        super.del(id);
    }

    @Override
    public void update(Employee employee) {
        //1.处理密码和盐值
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword()+salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);


        //2.修改员工信息
        super.update(employee);

        //先删除以前的中间表数据
        employeeMapper.delEmployeeRoleByEmpId(employee.getId());

        if (employee.getRole_id()!=null){
            //再添加新数据
            employeeMapper.addEmployeeRole(employee);
        }

        //3.修改Logininfo信息,通过id（Logininfo_id）修改
        Employee oldEmployee = employeeMapper.loadById(employee.getId());
        Logininfo oldLogininfo = logininfoMapper.loadById(oldEmployee.getLogininfo_id());


        //5个同名属性就是最新的数据
        BeanUtils.copyProperties(employee,oldLogininfo);
        oldLogininfo.setId(oldEmployee.getLogininfo_id());
        logininfoMapper.update(oldLogininfo);

    }
}
